package com.gooluke.spring.web;

import com.gooluke.spring.annotation.Autowired;
import com.gooluke.spring.annotation.Component;
import com.gooluke.spring.annotation.PostConstruct;
import com.gooluke.spring.annotation.Value;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.slf4j.bridge.SLF4JBridgeHandler;

import java.io.File;
import java.util.logging.LogManager;

/**
 * @author gooluke
 * description
 * datetime 2025-04-14 23:08
 */
@Component
public class MyTomcatServer {

    @Value("${server.port:8080}")
    private int port;
    @Value("${server.servlet.context-path:}")
    private String contextPath;

    @Autowired
    private MyDispatcherServlet dispatcherServlet;

    @PostConstruct
    public void start() throws LifecycleException {
        //日志桥接
        LogManager.getLogManager().reset();
        SLF4JBridgeHandler.removeHandlersForRootLogger();
        SLF4JBridgeHandler.install();
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(port);
        tomcat.getConnector();

        String contentPath = "";
        String docBase = new File(".").getAbsolutePath();
        Context context = tomcat.addContext(contentPath, docBase);
        tomcat.addServlet(contentPath, "helloServlet", dispatcherServlet);
        context.addServletMappingDecoded("/*", "helloServlet");
        tomcat.start();
        System.out.println("Tomcat started on port(s): " + port + " (http) with context path '" + contextPath + "'");
    }

}
